package com.wodan.zhongjinjicang.common.orm.bytesconverter;

import com.wodan.zhongjinjicang.common.orm.bytesconverter.impl.*;

import java.util.HashMap;
import java.util.Map;



/**
 * 转换器总入口
 * 
 * @ClassName: ConverterUtils
 * @author Administrator
 * @date 2015-1-10 下午3:51:39
 * @history
 * 
 */
public class ConverterUtils {
	/**
	 * 缓存单例转换器
	 */
	private static final Map<Class<?>, Converter> map = new HashMap<Class<?>, Converter>();
	static {
		map.put(String.class, new StringConverter());
		map.put(Integer.class, new IntegerConverter());
		map.put(Long.class, new LongConverter());
		map.put(long.class, new LongConverter());
		map.put(java.util.Date.class, new DateConverter());
		map.put(Boolean.class, new BooleanConverter());
		map.put(boolean.class, new BooleanConverter());
	}

	/**
	 * 创建转换器实例
	 * 
	 * @Description:
	 * @param clazz
	 * @return
	 */
	private static Converter create(Class<?> clazz) {
		Converter result = map.get(clazz);
		if (result == null) {
			throw new UnsupportedOperationException("unsupported class, class=" + clazz);
		}
		return result;
	}

	/**
	 * 将对象转换为string
	 * 
	 * @Description:
	 * @param obj
	 * @return
	 */
	public static String objectToString(Object obj) {
		Converter create = create(obj.getClass());
		return create.toString(obj);
	}

	/**
	 * 将string转换为对象
	 * 
	 * @Description:
	 * @param str
	 * @param clazz
	 * @return
	 */
	public static Object stringToObject(String str, Class<?> clazz) {
		Converter create = create(clazz);

		return create.fromString(str);
	}

	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null) {
			return true;
		}

		Converter create = create(obj.getClass());

		return create.isNullOrEmpty(obj);
	}
}
